package vue;




import modele.Echiquier;
import modele.SimpleService;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.finalprojet.R;

public class JeuEchec extends Activity{
	
	public static final int BLANC = 1;
    public static final int NOIR = 0;
    private int Couleur;
	

	int smsiphone;
	SoundPool wmp;
	ScrollView scroll;
	LinearLayout ChatMessage;
	EditText message;
	TextView chat;
	String pseudo= null;
	Messenger mService = null;
	boolean mIsBound;
	String Constant = null;
	Echiquier ech;
	Button send = null;
	final Messenger mMessenger = new Messenger(new IncomingHandler());
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.echiquier);
		
		Constant = "chat%"+getIntent().getStringExtra("num");
		((TextView)findViewById(R.id.chat)).setText(getIntent().getStringExtra("nom"));
		Couleur = Integer.parseInt(getIntent().getStringExtra("couleur"));
		pseudo = getIntent().getStringExtra("pseudo");
		//Couleur = getIntent().getIntExtra("couleur", 2);
		Log.e("pseudo",pseudo);
		message = (EditText)findViewById(R.id.chatMessageToSend);
	//	chat = (TextView)findViewById(R.id.ChatMessage);
		ech = new Echiquier(Couleur, this);
		ech.initCase();
		ech.initPos();
		ech.initOnClickListener();
		
		wmp = new SoundPool(16, AudioManager.STREAM_MUSIC, 0);
		smsiphone = wmp.load(getApplicationContext(), R.raw.iphone_sms_original, 1);		
	    doBindService();		
		
		scroll = (ScrollView)findViewById(R.id.scrollView1);
		ChatMessage = (LinearLayout)findViewById(R.id.ChatMessage);
		 
		  send = (Button)findViewById(R.id.chatSend);
	      message = (EditText) findViewById(R.id.chatMessageToSend);
 
	      send.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				    sendMessageToService(Constant+"%msg%"+message.getText().toString());
				    TextView Nextmess = new TextView(JeuEchec.this);
	                Nextmess.setBackgroundResource(R.drawable.rounded_to);
	                Nextmess.setText(message.getText());
	                Nextmess.setGravity(Gravity.LEFT);
	                Nextmess.setPadding(5, 10, 5, 10);
	                Nextmess.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
	                ChatMessage.addView(Nextmess);
	                scroll.fullScroll(ScrollView.FOCUS_DOWN);
	                message.setText("");
				
			}
		});
	      
	      
	     
	         
		
		
		
	} 
	
    
	void doBindService() {
			 
	          bindService(new Intent(this, SimpleService.class), mConnection, Context.BIND_AUTO_CREATE);
	         
	}
	
	 void sendMessageToService(String message) {

		 Log.e("sendMessageToService", "message");
	                Bundle b = new Bundle();
					b.putString("str1",message);
					Message msg = Message.obtain(null, SimpleService.MSG_SET_STRING_VALUE);
					msg.setData(b);
					try{
						mService.send(msg);
						
					}catch(Exception e){e.printStackTrace();}
				Log.e("sendMessageToService", "FIN");
	        
	    }
	
	
	@SuppressLint("HandlerLeak")
	class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            
            
            
            
            
            
            case SimpleService.MSG_SET_MSG:
            	/// peut etre erreur est la 
            	
                String str1 = msg.getData().getString("str1");
                Log.e("RECOIT MESSAGE",str1);
                //"coup%"+client_id+":"+coup)
                
                
                
                String[] tab = str1.split(":");
                
                
                
                if ( tab[0].equals(pseudo)) break;
                str1 = tab[1];
                
                
                
                
                
                TextView Nextmess = new TextView(JeuEchec.this);
                Nextmess.setBackgroundResource(R.drawable.rounded_from);
                Nextmess.setText(str1);
                Nextmess.setPadding(5, 10, 5, 10);
                LinearLayout.LayoutParams param= new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                param.gravity=Gravity.RIGHT;
                Nextmess.setLayoutParams(param); 
                

                ChatMessage.addView(Nextmess);
                scroll.fullScroll(ScrollView.FOCUS_DOWN);
                wmp.play(smsiphone, 1, 1, 1, 0, 1);

                break;
                
            case SimpleService.MSG_GET_PSEUDO:
                pseudo = msg.getData().getString("pseudo");
         
               
            case SimpleService.MSG_SET_COUP:
            	
            	
                String str5 = msg.getData().getString("str1");
                Log.e("RECOIT COUP",str5);
              
               
                
            
                String[] tabi = str5.split(":");
                Log.e("tabi[0]",tabi[0]) ;
                Log.e("pseudo",pseudo);
                Log.e("????",String.valueOf(!tabi[0].equalsIgnoreCase(pseudo)));
                 if ( !tabi[0].equalsIgnoreCase(pseudo)) 
                	 {ech.coupAdverse(tabi[1]);}
                
                
                 
                 
                 
                break;
               
         
                
            default:
                super.handleMessage(msg);
            }
        }
    }
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
           
            try {
                Message msg = Message.obtain(null, SimpleService.MSG_REGISTER_CLIENT);
                msg.replyTo = mMessenger;
                mService.send(msg);
              
            } catch (RemoteException e) {
                // In this case the service has crashed before we could even do anything with it
            }
        }

        public void onServiceDisconnected(ComponentName className) {

            mService = null;
            
        }
    };

	public void sendCoupToService(String coup) {
		  Bundle b = new Bundle();
			b.putString("str1",Constant+"%coup%"+Couleur +"%"+ coup); // style chat%0%coup%0%F2F4
			Message msg = Message.obtain(null, SimpleService.MSG_SET_STRING_VALUE);
			msg.setData(b);
			try{ 
				mService.send(msg);
				
			}catch(Exception e){e.printStackTrace();}
		
	}

}
